package com.erlinyou.im.web.wshandler;

import java.io.IOException;
import java.net.URI;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.erlinyou.im.common.uuid.UUIDGenerator;
import com.erlinyou.im.model.offline.OfflineMessage;
import com.erlinyou.im.service.chat.IChatCurrwinService;
import com.erlinyou.im.service.offline.IOfflineMessageService;
import com.erlinyou.im.web.controller.base.SiteUtil;
import com.erlinyou.im.web.controller.chat.ChatMessageController;
import com.erlinyou.travel.model.user.TUser;

@Component
public class ChatWebSocketHandler extends TextWebSocketHandler{
	private static Logger logger = LoggerFactory.getLogger(ChatWebSocketHandler.class);
	@Resource
	private IChatCurrwinService chatReadFlagService;
	
	@Resource
	private IOfflineMessageService offlineMessageService;
	
    @PostConstruct
    public void init(){
    	logger.info("***************初始化websocket**************");
    }
	
    @Override
    public void afterConnectionEstablished(final WebSocketSession session) throws IOException {
	    	LocalWebSocketSession localWebSocketSession = new LocalWebSocketSession(session);
	    	TUser user = SiteUtil.getCurrUser(session);
	    	
    	if(user!=null) {
	    	WSSManager.addSession(user.getUserid(), localWebSocketSession);
	    	
	    	connectionHandler(localWebSocketSession, user);
    	}else {
    		String url = session.getUri().toString();
        	String xauthtoken = url.split("=")[1];
    		try {
				WSSManager.addSession(Long.valueOf(xauthtoken), localWebSocketSession);
			} catch (NumberFormatException e) {
				logger.error(xauthtoken+"->未登录时传xauthtoken必须为Long型:"+e);
			}
    	}
    }

    /*
     * 登录成功之后处理
     * 1	离线消息
     * 2	推送状态给好友
     * @param localWebSocketSession
     * @param user
     * @throws IOException
     */
	private void connectionHandler(LocalWebSocketSession localWebSocketSession, TUser user) throws IOException{
		//2 TODO 清除队列
		
		//登录成功推送离线消息
    	List<OfflineMessage> offlineList = offlineMessageService.findByUserid(user.getUserid());
    	if(offlineList!=null && offlineList.size()>0){
    		for (OfflineMessage offlineMessage : offlineList) {
    			String content = offlineMessage.getContent();
    			localWebSocketSession.sendLocalMessage(content);
			}
    	}
    	
    	//TODO 推送状态给好友
    	
    	
    	//TODO 监听集群消息到来,推送客户端
	}
	/*
	 * 断开连接之后
	 * 
	 */
	private void disConnectionHandler(TUser user) {
		//1 TODO 推送状态给好友
		
		//2 TODO 清除队列
		
		//删除设置的当前会话
		chatReadFlagService.deleteByUserid(user.getUserid());
	}
	
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    	System.out.println(message);
	}
    @Override
    public void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
    	System.out.println(message);
	}
    @Override
    public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
        if(wss.isOpen()){
            wss.close();
        }
       logger.debug("WebSocket error:",thrwbl);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus cs) {
    	TUser user = SiteUtil.getCurrUser(session);
    	if(user != null){
    		WSSManager.removeSession(user.getUserid(),session);
    		disConnectionHandler(user);
    	}
    	
    	
    }
    
}